/*
 * FileHandler Class is created for IO operations
 * and File Streaming Tasks inside application
 */
package com.meraklisina.latexeditor;

import java.io.*;

/**
 *
 * @author kursattopcu
 */
public class FileHandler {

    public String filePath = "";
    /*
     * Open File Method calls FileChooser Control
     * gets selected file path and returns file content as string
     * */

    public String OpenFile() {
        FileChooser chooser = new FileChooser();
        chooser.ShowChooseDialog(null);
        File inputFile = chooser.GetSelectedFile();
        if (inputFile == null) {
            return null;
        }
        this.filePath = inputFile.toString();

        String documentString = "";
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream(inputFile.toString());
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                documentString += strLine + "\n";
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
        return documentString;
    }

    /*
     * SaveFile method takes filePath and data as string as parameters
     * and writes data into file in given path
     * returns false if any exception occurs and true if succeeds
     * */
    public Boolean SaveFile(String filePath, String data) {
        FileOutputStream out; // declare a file output object
        PrintStream p; // declare a print stream object

        try {
            // Create a new file output stream            
            out = new FileOutputStream(filePath);

            // Connect print stream to the output stream
            p = new PrintStream(out);

            p.println(data);

            p.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
